﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using SoftwareConsulting.BI11.Studio.Core.Project.Metadata;
using SoftwareConsulting.BI11.Studio.Core.Project.Metadata.Extensions;
using SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.SituationsHierarchy;
using SoftwareConsulting.BI11.Studio.UI.Properties;
using SoftwareConsulting.BI11.Studio.InternalServices;

namespace SoftwareConsulting.BI11.Studio.UI.ProjectExplorer
{
    /// <summary>
    /// Класс диалога поиска ситуации
    /// </summary>
    public partial class FindObjectDialog : RestorableForm
    {
        private ProjectExplorerForm _projectExplorerLink; //для связи с формой обозревателя проекта
        private MetadataObjectsVisibleTypes _types; //типы объектов
        private List<IMetadataObjectDescriptor> _result; //найденные объекты

        /// <summary>
        /// Осуществляет поиск объекта
        /// </summary>
        private void Search()
        {
            ComboBox.ObjectCollection its = ResultComboBox.Items;
            its.Clear();
            string s = SearchStringTextBox.Text.Trim();
            string findstring = s.ToUpper(CultureInfo.CurrentCulture);
            IEnumerable<IMetadataObjectDescriptor> objs = _types.All ? _projectExplorerLink.ProjectLink.RepositoryLink.WalkObjects() : _projectExplorerLink.ProjectLink.RepositoryLink.WalkObjects(_types.Kind);
            var query = from desc in objs
                      where desc.Name.ToUpper(CultureInfo.CurrentCulture).Contains(findstring)
                      orderby desc.Name
                      select desc;
            _result = new List<IMetadataObjectDescriptor>();
            int maxNum = 100;
            int realNum = 0;
            if ((realNum = query.Count()) > maxNum)
            {
                GeneralMethods.ShowInformation(string.Format(Resources.BI_PROJECTEXPLORER_FINDDIALOG_MANY_RESULTS, realNum, maxNum));
            }
            foreach (var item in query.Take(maxNum))
            {
                _result.Add(item);
                its.Add(item.Name);
            }            
            if (its.Count > 0)
            {
                ResultComboBox.SelectedIndex = 0;
            }
            else
            {
                GeneralMethods.ShowInformation(Resources.BI_PROJECTEXPLORER_FINDDIALOG_NO_RESULTS, Resources.BI_PROJECTEXPLORER_FINDDIALOG_SEARCH_END);                
            }
        }

        /// <summary>
        /// Переходит к указанному объекту
        /// </summary>
        private void GotoObject()
        {
            int index = ResultComboBox.SelectedIndex;
            IMetadataObjectDescriptor objDesc = _result[index];
            switch (objDesc.Kind)
            {
                case MetadataObjectKind.Situation:
                    SituationsArea _curSA = _projectExplorerLink.MainFormLink.HierarchyForm.CurrentSituationsArea;
                    //TODO _curSA.GotoSituationBoxBySituation(objinfo.Label);
                    _projectExplorerLink.MainFormLink.HierarchyForm.ReadScrollInfo(); //чтобы после закрытия диалога скролл не уехал        
                    break;
                default:
                    _projectExplorerLink.FocusObject(objDesc);
                    break;
            }
        }

        public FindObjectDialog(ProjectExplorerForm projectExplorerLink, MetadataObjectsVisibleTypes visibleTypes)
        {
            _projectExplorerLink = projectExplorerLink;
            _types = visibleTypes;
            InitializeComponent();
        }

        private void SituationsComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {            
            GotoObject();
        }

        private void SearchButton_Click(object sender, EventArgs e)
        {
            Search();
        }

        private void SearchStringTextBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Search();                
            }            
        }

        /// <summary>
        /// Инициализация диалога
        /// </summary>
        private void Initialize()
        {
            if (!_types.All)
            {
                Text = Text + " - " + _types.Kind.ToUserString();
            }
        }

        private void FindObjectDialog_Load(object sender, EventArgs e)
        {
            Initialize();
        }
    }
}
